let getTreeCheckedId, uncheckedTree
function createTree (datas, treeWrap, randomId, selectAll) {
  console.log(selectAll)
  let html = ''
  html += '<div class="tree-container"><div class="tree-list-wrap" id="tree1' + randomId + '"></div><div class="tree-list-wrap" id="tree2' + randomId + '"></div><div class="tree-list-wrap" id="tree3' + randomId + '"></div><div class="tree-checked-wrap"><div class="checked-tree-wrap" id="tree4' + randomId + '"></div></div></div>'

  $(treeWrap).html(html)

  var baseData = [
    {
      id: '6000001',
      title: '内部',
      arryName: 'innerList',
      nextArry: datas.innerList ? formatCompanyData(datas.innerList) : []
    },
    {
      id: '6000002',
      title: '外部',
      arryName: 'outerList',
      children: [
        {
          id: '6000003',
          pid: '6000002',
          title: '好友公司',
          arryName: 'friendList',
          nextArry: datas.outerList.friendList ? formatCompanyData(datas.outerList.friendList) : []
        },
        {
          id: '6000004',
          pid: '6000002',
          title: '客商',
          arryName: 'customerList',
          nextArry: datas.outerList.customerList ? formatCustomerData(datas.outerList.customerList) : []
        },
        {
          id: '6000005',
          pid: '6000002',
          title: '供应商',
          arryName: datas.outerList.supplyList ? formatCompanyData(datas.outerList.supplyList) : [],
        }
      ]
    }
  ]

  layui.use(function () {
    var tree = layui.tree;

    renderTree()

    function renderTree () {
      tree.render({
        elem: '#tree1' + randomId,  //绑定元素
        showCheckbox: true,
        onlyIconControl: true,
        data: baseData,
        id: 'demoId1' + randomId,
        click: function (obj) {
          if ($(treeWrap).find('#tree3' + randomId).children().length) {
            // tree.reload('demoId3', {data:[]});
          }
          // 二级树
          if (obj?.data?.nextArry) {
            Object.keys(obj.data.nextArry).forEach(item => {
              obj.data.nextArry[item].spread = true
              obj.data.nextArry[item].pid = obj.data.id // 子集赋予父id
              if (obj.data.nextArry[item].children) {
                obj.data.nextArry[item].children.forEach(items => {
                  items.rootId = obj.data.id
                })
              }
            })
          }

          renderTree2(obj.data.nextArry)
        },
        oncheck: function (obj) {
          if ($(treeWrap).find('#tree3' + randomId).children().length) {
            tree.reload('demoId3' + randomId, { data: [] });
          }

          if (obj.data.pid) {
            let childCheckArry = []
            let pidIndex = baseData.findIndex(item => { return item.id === obj.data.pid })
            let nowNode = $(treeWrap).find('#tree1' + randomId).find('input[value="' + obj.data.pid + '"]')
            let childCheck = nowNode.parent().parent().next().find('input')

            for (let i = 0; i < childCheck.length; i++) {
              childCheckArry.push($(treeWrap).find(childCheck[i]).prop('checked'))
            }

            let halfCheck = childCheckArry.some(item => { return item === true })
            let allCheck = childCheckArry.every(item => { return item === true })

            if (halfCheck && !allCheck) {
              baseData[pidIndex].checked = false
              nowNode.prop('checked', false).next().addClass('layui-form-half-checked')
            }

            if (allCheck) {
              baseData[pidIndex].checked = true
              nowNode.prop('checked', true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
            }
          }

          let nextArry = []
          obj.checked ? obj.data.checked = true : obj.data.checked = false
          // 当前树
          if (obj?.data?.children?.length) {
            obj.data.children = changeChildrenStatus(obj.data.children, obj.checked)
          } else if (obj?.data?.nextArry) {
            nextArry = changeChildrenStatus(obj.data.nextArry, obj.checked)
          }

          // 对比当前选择和二级树是否为父子级关系 如果是刷新二级树数据
          let tree2Data = $(treeWrap).find('#tree2').find('input[type="checkbox"]').val()
          let isParent = nextArry.some(item => { return item.id === tree2Data })
          if (isParent) { // 如过是所属关系刷新数据
            renderTree2(obj.data.nextArry)
          }
          const checketList = getCheckedList()
          createCheckedDom(checketList)
        }
      })
    }


    function renderTree2 (itemData) {
      let data = []
      if (!itemData) {
        itemData = []
      }
      Object.keys(itemData).forEach(item => {
        data.push(itemData[item])
      })

      tree.render({
        elem: '#tree2' + randomId,  //绑定元素
        showCheckbox: true,
        onlyIconControl: true,
        data: data,
        id: 'demoId2' + randomId,
        click: function (obj) {
          // 三级树
          if (obj?.data?.childrens?.length) {
            obj.data.childrens.forEach(item => {
              item.spread = true
              item.rootId = obj.data.rootId
              item.pid = obj.data.id // 子集赋予父id
              if (item.childrens) {
                item.childrens.forEach(items => {
                  items.rootId = obj.data.rootId
                })
              }
            })
          }
          renderTree3(obj.data)
        },
        oncheck: function (obj) {
          obj.checked ? obj.data.checked = true : obj.data.checked = false

          let tree2CheckArry = []
          let tree2CheckN = $('#tree2' + randomId).find('input[type="checkbox"]')
          for (let i = 0; i < tree2CheckN.length; i++) {
            tree2CheckArry.push($(tree2CheckN[i]).prop('checked'))
          }

          // 检测是否全部取消选中 去取消一级树选中
          let noParentCheck = tree2CheckArry.every(item => { return !item })
          let isParentCheck = tree2CheckArry.every(item => { return item })

          // 父节点操作
          // let nodeId = obj.data.rootId ? obj.data.rootId : obj.data.pid
          let setNode = checkedParentNode(obj.data.pid ?? obj.data.rootId)
          let tree2AllvalNode
          if ($(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').length) {
            tree2AllvalNode = $(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').find('input')
          } else {
            tree2AllvalNode = $(treeWrap).find('#tree2' + randomId).find('input')
          }

          let tree2AllvalArry = []

          setTimeout(() => {
            for (let j = 0; j < tree2AllvalNode.length; j++) {
              tree2AllvalArry.push($(tree2AllvalNode[j]).prop('checked'))
            }
            let noallCheck = tree2AllvalArry.some(item1 => { return !item1 })
            let isallCheck = tree2AllvalArry.some(item1 => { return item1 })
            let allCheckTree2 = tree2AllvalArry.every(item1 => { return item1 === true })
            let hasHalf = $(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').find('.layui-form-half-checked').length


            if ((isallCheck && noallCheck && !allCheckTree2) || hasHalf) {
              if ($(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').length) {
                $(treeWrap).find('#tree2' + randomId + ' .layui-tree-set').find('input').eq(0).prop('checked', false).next().addClass('layui-form-half-checked')
              }
              setNode.prop('checked', false).next().addClass('layui-form-half-checked')
            } else {
              if (allCheckTree2) {
                if (obj?.data?.children?.length) {
                  $(treeWrap).find('#tree2' + randomId + ' .layui-tree-set').find('input').eq(0).prop('checked', true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
                }
                setNode.prop('checked', true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
              } else {
                if (obj.data.level === 0 && obj.data.pid) {
                  parentNode = checkedParentNode(obj.data.pid)
                  parentNode.parent().find('.layui-form-checkbox').eq(0).removeClass('layui-form-half-checked layui-form-checked')
                }
              }
            }
          })

          if (noParentCheck) { // 全部取消
            if (setNode.prop('checked')) {
              setNode.next().click()
            }
          }

          if (isParentCheck) { // 全部选中
            if (!setNode.prop('checked')) {
              setNode.next().click()
            }
          }


          // 操作3级
          let nextArry = []
          if (obj?.data?.childrens) {
            obj.data.childrens.forEach(item => {
              obj.checked ? item.checked = true : item.checked = false
              item.spread = true
            })
          }

          // 下级树 （部分需要写成递归）
          if (obj?.data?.childrens) {
            Object.keys(obj.data.childrens).forEach(item => {
              // 有子项的不能直接设置checked !obj.data.nextArry[item].children.length
              if (obj.checked && !obj.data.childrens[item]?.children?.length) {
                obj.data.childrens[item].checked = true
              } else {
                obj.data.childrens[item].checked = false
                // 如果有子集把所有子集设置选中  （只局限一组数据，根据需求变动下）
                if (obj.data.childrens[item].children) {
                  obj.data.childrens[item].childrens.forEach(item => {
                    obj.checked ? item.checked = true : item.checked = false
                    // obj.rootId = obj.data.id
                  })
                }
              }

              obj.data.childrens[item].pid = obj.data.id // 子集赋予父id
              nextArry.push(obj.data.childrens[item])
            })
          }

          // 对比当前选择和三级级树是否为父子级关系 如果是刷新三级树数据
          let tree3Data = $(treeWrap).find('#tree3' + randomId).find('input[type="checkbox"]').val()
          let isParent = nextArry.some(item => { return item.id === tree3Data })
          if (isParent) { // 如过是所属关系刷新数据
            renderTree3(obj.data)
          }
          const checketList = getCheckedList()
          createCheckedDom(checketList)
        }
      })
    }

    function renderTree3 (data) {
      if (!data) { return }
      let datas = formatDepartmentData(data.childrens)
      tree.render({
        elem: '#tree3' + randomId,  //绑定元素
        showCheckbox: true,
        data: datas,
        id: 'demoId3' + randomId,
        click: function (obj) {

        },
        oncheck: function (obj) {
          obj.checked ? obj.data.checked = true : obj.data.checked = false

          let tree3CheckArry = []
          let tree3CheckN = $(treeWrap).find('#tree3' + randomId).find('input[type="checkbox"]')
          for (let i = 0; i < tree3CheckN.length; i++) {
            tree3CheckArry.push($(treeWrap).find(tree3CheckN[i]).prop('checked'))
          }

          // 检测是否全部取消选中 去取消二级树选中
          let noParentCheck = tree3CheckArry.every(item => { return !item })
          let isParentCheck = tree3CheckArry.every(item => { return item })

          // 不为全选
          let halfParentCheck = tree3CheckArry.some(item => { return !item })

          // 父节点操作
          let setNode1 = checkedParentNode(obj.data.rootId)

          let setNode = checkedParentNode(obj.data.pid)
          let tree2AllvalNode

          if ($(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').length) {
            tree2AllvalNode = $(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').find('input')
          } else {
            tree2AllvalNode = $(treeWrap).find('#tree2' + randomId).find('input')
          }

          let tree2AllvalArry = []

          setTimeout(() => {
            for (let j = 0; j < tree2AllvalNode.length; j++) {
              tree2AllvalArry.push($(treeWrap).find(tree2AllvalNode[j]).prop('checked'))
            }
            let noallCheck = tree2AllvalArry.some(item1 => { return !item1 })
            let isallCheck = tree2AllvalArry.some(item1 => { return item1 })
            let allCheckTree2 = tree2AllvalArry.every(item1 => { return item1 })
            let hasHalf = $(treeWrap).find('#tree2' + randomId + ' .layui-tree-pack').find('.layui-form-half-checked').length


            if ((isallCheck && noallCheck && !allCheckTree2) || hasHalf) {
              $(treeWrap).find('#tree2' + randomId + ' .layui-tree-set').find('input').eq(0).prop('checked', false).next().addClass('layui-form-half-checked')
              setNode1.prop('checked', false).next().addClass('layui-form-half-checked')
            } else {
              if (allCheckTree2 && tree2AllvalArry.length) {
                $(treeWrap).find('#tree2' + randomId + ' .layui-tree-set').find('input').eq(0).prop('checked', true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
                setNode1.prop('checked', true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
              }
            }
          })

          if (halfParentCheck) {
            if (!noParentCheck) {
              setNode.next().addClass('layui-form-half-checked')
              setNode.prop('checked', false)
              setNode1.next().addClass('layui-form-half-checked')
              setNode1.prop('checked', false)
            } else {
              setNode.prop('checked', true)
              setNode.next().addClass('layui-form-checked')
              setNode.next().removeClass('layui-form-half-checked')
              setNode1.prop('checked', true)
              setNode1.next().addClass('layui-form-checked')
              setNode1.next().removeClass('layui-form-half-checked')
            }
          }

          if (noParentCheck) { // 全部取消
            if (setNode.prop('checked')) {
              setNode.next().click()
            }
          }

          if (isParentCheck) { // 全部选中
            if (obj.data.pid !== '100016') {
              if (!setNode.prop('checked')) {
                // setNode.next().click()
                data.checked = true
                setNode.prop('checked', true)
                setNode.next().addClass('layui-form-checked')
                setNode.next().removeClass('layui-form-half-checked')
              }
            }
          }

          if (obj.data.hasOwnProperty('children') && obj.data.children) {
            changeChildrenStatus(obj.data.children, obj.checked)
          } else if (obj.data.hasOwnProperty('childrens') && obj.data.childrens) {
            changeChildrenStatus(obj.data.childrens, obj.checked)
          }

          const checketList = getCheckedList()
          createCheckedDom(checketList)
        }
      })
    }


    function formatDepartmentData (data, isChecked) {
      if (!data) {
        return []
      }
      let arr = []
      data.map(obj => {
        if (obj.type !== 'company') {
          // obj.checked = isChecked
          if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
            obj.children = obj.childrens
            formatDepartmentData(obj.childrens, isChecked)
          }
          arr.push(obj)
        }
      })
      return arr
    }

    function checkedParentNode (id) {
      return $(treeWrap).find('input[value="' + id + '"]')
    }


    function getCheckedList (data = baseData, arr = []) {
      data.map(obj => {
        if (obj.checked) {
          arr.push(obj)
        } else {
          let dataList = []

          if (obj.hasOwnProperty('children') && obj.children.length > 0) {
            dataList = obj.children
          } else if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
            dataList = obj.childrens
          } else if (obj.hasOwnProperty('nextArry') && Object.values(obj.nextArry).length > 0) {
            dataList = Object.values(obj.nextArry)
          }
          getCheckedList(dataList, arr)
        }
      })
      return arr
    }

    function unchecked (t) {
      const id = $(treeWrap).find(t).parent().attr('data-id')
      const note = checkedParentNode(id)

      note.next().click()
    }

    uncheckedTree = unchecked
  });

  function getCheckedId (data = baseData, arr = []) {
    data.map(obj => {
      if (obj.checked && obj.type) {
        arr.push(`addTopicPermissionList_${obj.type}_${obj.id}`)
      }
      let dataList = []

      if (obj.hasOwnProperty('children') && obj.children.length > 0) {
        dataList = obj.children
      } else if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
        dataList = obj.childrens
      } else if (obj.hasOwnProperty('nextArry') && Object.values(obj.nextArry).length > 0) {
        dataList = Object.values(obj.nextArry)
      }
      getCheckedId(dataList, arr)
    })
    return arr
  }

  function createCheckedDom (list) {
    let html = ''

    list.map(obj => {
      html += `<div class="tree-checked-list" data-id="${obj.id}"><p>${obj.title}</p><i class="layui-icon layui-icon-close" data-toggle="tooltip" data-placement="top" title="${obj.title}" onclick="uncheckedTree(this)"></i></div>`
    })

    $(treeWrap).find('#tree4' + randomId).html(html)
  }

  getTreeCheckedId = getCheckedId
}

function formatCompanyData (data, t, id = 0) {
  Object.keys(data).map(k => {
    data[k].ftype = t
    data[k].name ? data[k].title = data[k].name : ''
    data[k].pid = id
    if (data[k].hasOwnProperty('children') && Object.keys(data[k].children).length > 0) {
      formatCompanyData(data[k].children, t, data[k].id)

      data[k].childrens = Object.values(data[k].children)
      if (data[k].type === 'company' || data[k].type === 'customer') {
        let arr = []
        Object.values(data[k].children).map(obj => {
          if (obj.type === 'company' || obj.type === 'customer') {
            arr.push(obj)
          }
        })
        data[k].children = arr
      }
    }
  })
  return Object.values(data)
}

function formatCustomerData (data, t, id) {
  let arr = []
  Object.values(data).map(obj => {
    obj.ftype = t
    obj.pid = id
    obj.title = obj.name
    arr.push(obj)
  })
  return arr
}

function changeChildrenStatus (dataList, isChecked) {
  dataList.map(dataObj => {
    let childList = []

    dataObj.checked = isChecked

    if (dataObj.hasOwnProperty('children') && dataObj.children.length > 0) {
      childList = dataObj.children
    } else if (dataObj.hasOwnProperty('childrens') && dataObj.childrens.length > 0) {
      childList = dataObj.childrens
    } else if (dataObj.hasOwnProperty('nextArry') && Object.values(dataObj.nextArry).length > 0) {
      childList = Object.values(dataObj.nextArry)
    }

    if (childList) {
      childList = changeChildrenStatus(childList, isChecked)
    }
  })
  return dataList
}